//
//  wkViewController.m
//  WKWebView
//
//  Created by RYX on 2018/11/8.
//  Copyright © 2018年 tuobu. All rights reserved.
//

#import "wkViewController.h"
#import <WebKit/WebKit.h>
#import "YYCategories.h"
#import "CompanyNewsModel.h"
#import "HomeList.h"
#import "NSData+Base64.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "WXApi.h"


@interface wkViewController ()<WKNavigationDelegate,WKUIDelegate>
{
    NSString *utf8String;
    NSString *title;
    NSString *description;
    NSString *previewImageUrl;
}
//@property (nonatomic,strong) UIView *redView;
@property (nonatomic,strong) UIView *bgView;
@property (nonatomic, strong) UIView *shareView;
@property (nonatomic,strong) WKWebView *webView;
@property (nonatomic, strong) UIProgressView *myProgressView;

@end

@implementation wkViewController

- (WKWebView *)webView{
    
    if (!_webView) {
        
        _webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        NSString *url = [HomeList sharedInstance].selectedNew.url;
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
        [_webView loadRequest:request];
    }
    
    return _webView;
}

- (UIProgressView *)myProgressView {
    
    if (_myProgressView == nil) {
        
        _myProgressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0)];
        _myProgressView.tintColor = BLUECOLOR;
        _myProgressView.trackTintColor = BASECOLOR;
        
    }
    
    return _myProgressView;
    
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:YES];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (UIView *)bgView{
    
    if (!_bgView) {
        
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        [_bgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didBgView)]];
    }
    
    return _bgView;
}

- (void)didBgView{

    MJWeakSelf
    [UIView animateWithDuration:0.2 animations:^{
        
        weakSelf.shareView.y = SCREEN_HEIGHT + 50;
        weakSelf.bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        
    } completion:^(BOOL finished) {
        
        [weakSelf.bgView removeFromSuperview];
    }];
    
}

- (UIView *)shareView{
    
    if (!_shareView) {
        
        _shareView = [[[NSBundle mainBundle] loadNibNamed:@"RedShareView" owner:self options:nil] objectAtIndex:0];
        _shareView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 105);
        _shareView.y = SCREEN_HEIGHT + 50;
        
    }
    
    return _shareView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.autoresizesSubviews = NO;
    
    [self setNavBar];
    
    [self.view addSubview:self.webView];
    [self.view addSubview:self.myProgressView];
    [self.view addSubview:self.shareView];
    
    MJWeakSelf
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(weakSelf.view);
        
    }];
    
    [self loadData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shareSuccessBlock) name:@"SHARESUCCESS" object:nil];
}

- (void)setNavBar{
    
    [self setNavBarWithTitle:@"行业新闻"];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //修改按钮向右偏移10 point
    [rightBtn setFrame:CGRectMake(14, 0.0, 44.0, 44.0)];
    //修改方法
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 44.0, 44.0)];
    [view addSubview:rightBtn];
    [rightBtn addTarget:self action:@selector(onRightBtn) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setImage:[UIImage imageNamed:@"img_shareBtn"] forState:UIControlStateNormal];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:view];
    self.navigationItem.rightBarButtonItem = item;
}

- (void)onRightBtn{
    
    if (self.shareView.y >= ScreenHeight){
        
        [self.view insertSubview:self.bgView belowSubview:self.shareView];
        
        MJWeakSelf
        [UIView animateWithDuration:0.7 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:0 animations:^{
            
            weakSelf.shareView.y = SCREEN_HEIGHT - 105 - iPhoneX_Top;
            weakSelf.bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
            
        } completion:nil];
        
    }else{
        
        
        [self didBgView];
        
    }
}

#pragma mark - 分享成功回调
- (void)shareSuccessBlock{
    
    [self didBgView];
    [self showMBPError:@"分享成功"];
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    
}
- (void)onbtn:(UIButton *)btn{
    
    MJWeakSelf
    
//    [UIView animateWithDuration:0.7 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:0 animations:^{
//
//        weakSelf.shareView.y = SCREEN_HEIGHT - 105;
//
//
//    } completion:nil];
    
    if (self.shareView.y >= ScreenHeight){
        
        [self.view insertSubview:self.bgView belowSubview:self.shareView];
        
        [UIView animateWithDuration:0.7 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:0 animations:^{
            
            weakSelf.shareView.y = SCREEN_HEIGHT - 105;
            weakSelf.bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
            
        } completion:nil];
        
    }else{
        
        
        [self didBgView];
        
    }
    
//    if (self.redView.y < 0) {
//
//        [self.view insertSubview:self.bgView belowSubview:self.redView];
//
//        [UIView animateWithDuration:0.7 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:0 animations:^{
//
//            weakSelf.redView.centerY = self.view.centerY;
//            weakSelf.bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
//
//        } completion:nil];
//
//    }else{
//
//
//        [self didBgView];
//
//    }

}
- (IBAction)onCloseBtn:(UIButton *)sender {
    
    [self didBgView];
    
}

- (IBAction)onShareBtn:(UIButton *)sender {
    
    MJWeakSelf
    
    [UIView animateWithDuration:0.7 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:0 animations:^{
        
        weakSelf.shareView.y = SCREEN_HEIGHT - 105;
        
        
    } completion:nil];
    
    

}

- (void)loadData{
    
    CompanyNewsModel *model = [HomeList sharedInstance].selectedNew;
    utf8String = model.url;
    title = model.bt;
    description = @"畅享合伙人";
    previewImageUrl = model.img;
    
}


- (IBAction)onShareWX:(UIButton *)sender {
    
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = title;//主标题
    message.description = description;//描述
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:previewImageUrl]];
    UIImage *img = [UIImage imageWithData:data];
    [message setThumbImage:[ImgManager getSimpleImg:img]];

    WXWebpageObject *webobject = [WXWebpageObject object];
    webobject.webpageUrl = utf8String;
    message.mediaObject = webobject;

    SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
    req.message = message;
    req.scene = WXSceneSession;
    [WXApi sendReq:req];
    
}
- (IBAction)onSharePYQ:(UIButton *)sender {
    
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = title;//主标题
    message.description = description;//描述
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:previewImageUrl]];
    UIImage *img = [UIImage imageWithData:data];
    [message setThumbImage:[ImgManager getSimpleImg:img]];
    
    WXWebpageObject *webobject = [WXWebpageObject object];
    webobject.webpageUrl = utf8String;
    message.mediaObject = webobject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
    req.message = message;
    req.scene = WXSceneTimeline;
    [WXApi sendReq:req];
    
}
- (IBAction)onShareQQ:(UIButton *)sender {

    QQApiTextObject *txtObj = [QQApiNewsObject objectWithURL:[NSURL URLWithString:utf8String] title:title description:description previewImageURL:[NSURL URLWithString:previewImageUrl]];
    
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:txtObj];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [QQApiInterface sendReq:req];
    });
    
}
- (IBAction)onShareKJ:(UIButton *)sender {
    
    CompanyNewsModel *model = [HomeList sharedInstance].selectedNew;
    NSString *utf8String = model.url;
    NSString *title = model.bt;
    NSString *description = @"畅享合伙人";
    NSString *previewImageUrl = model.img;
    QQApiTextObject *txtObj = [QQApiNewsObject objectWithURL:[NSURL URLWithString:utf8String] title:title description:description previewImageURL:[NSURL URLWithString:previewImageUrl]];
    
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:txtObj];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [QQApiInterface SendReqToQZone:req];
    });
}

#pragma mark - 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        self.myProgressView.alpha = 1.0f;
        [self.myProgressView setProgress:newprogress animated:YES];
        if (newprogress >= 1.0f) {
            
            [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                
                self.myProgressView.alpha = 0.0f;
                
            } completion:^(BOOL finished) {
                
                [self.myProgressView setProgress:0 animated:NO];
                
            }];
            
        }
        
    } else {
        
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        
    }
    
}


@end
